<template>
	<view class="page" :style="{'overflow':show?'hidden':''}">
		<scroll-view scroll-y="true" class="scroll-Y" :key="1" v-if="!show">
			<view class="context">
				<view class="title">
					<text>不知道写什么？试试这个</text>
					<image style="width: 48rpx;height: 24rpx;margin: 0 4px;" src="/static/create/create_finger.png">
					</image>
					<text style="color: #f1445d" @click="select('诛仙')">诛仙</text>
				</view>
				<view class="context-title">
					<text>小说类型</text>
					<text class="context-title-tip"></text>
				</view>
				<view class="context-tone">
					<view class="context-tone-item" v-for="(item,index) in toneList" :key="index"
						@click="changeTone(item,index)" :class="{'context-tone-item-select':index==toneIndex}">
						{{item.text}}</view>
				</view>
				<!--        -->
				<!--        -->
				<view class="context-title">
					<text>选择风格</text>
					<text class="context-title-tip"></text>
				</view>
				<view class="context-tone">
					<view class="context-tone-item" v-for="(item,index) in styleList" :key="index"
						@click="changeStyle(item,index)" :class="{'context-tone-item-select':index==styleIndex}">
						{{item.text}}
					</view>
				</view>
				<!--        -->
				<view class="context-tip">
					<view class="context-tip-left">
						<text>结果字数</text>
						<text class="context-tip-left-tip">*</text>
					</view>
					<!--            <view class="context-tip-right">至少包含10个字</view>-->
				</view>
				<view class="context-textarea" style="height: 80rpx">
					<textarea :value="message" placeholder="请输入字数(<= 1000)"
						placeholder-style="color:#999999;font-size:24rpx" :maxlength="20" @input="changeMessage"
						class="context-textarea-input" style="margin: -9rpx 0 0 0"></textarea>
					<!-- <view class="context-textarea-max">{{message.length}}/20</view> -->
				</view>
				<!--        -->
				<view class="context-tip">
					<view class="context-tip-left">
						<text>主题/关键词</text>
						<text class="context-tip-left-tip">*</text>
					</view>
					<!--            <view class="context-tip-right">至少包含50个字</view>-->
				</view>
				<view class="context-textarea">
					<textarea :value="writing" placeholder="请输入您想要的内容主题或者关键词。内容越详细越准确，生成的内容越好哦！"
						placeholder-style="color:#999999;font-size:24rpx" @input="changeValue" :maxlength="100"
						class="context-textarea-input"></textarea>
					<view class="context-textarea-max">{{writing.length}}/100</view>
				</view>
				<view class="button" @click="create"
					:style="{'background':(writing.length>0&&message.length>0)?'linear-gradient(180deg, #E9556A 0%, #F97A8C 100%);':'#FFEEF0'}">
					开始生成</view>
				<view style="height: 80rpx"></view>
			</view>
		</scroll-view>
		<view class="page-view" v-if="show" :key="2">
			<view class="answer">
				<view class="answer-value">{{title?title:writing}}</view>
				<view class="answer-textarea">
					<textarea :value="creativeResult" :maxlength="-1" class="answer-textarea-input"></textarea>
					<view class="answer-fontLength">共{{creativeResult.length}}字</view>
				</view>
			</view>
			<view class="tabbar">
				<view class="tabbar-item" @click="clickTab(item,index)" v-for="(item, index) in tabbarList"
					:key="index">
					<view>
						<image style="width: 38rpx;height: 38rpx;margin-top:8rpx" :src="item.src"></image>
					</view>
					<view style="margin-left:30rpx">{{item.text}}</view>
				</view>
			</view>
		</view>
		<!--  进度条  -->
		<view class="schedule-page" v-if="scheduleShow">
			<view class="schedule-box">
				<view class="schedule-text">{{text}}</view>
				<view class="lineBox">
					<view class="lineAnimation" v-for="(item,index) in arrIndex" :key="index"
						:style="{'width':item.width+'%'}">
						<view v-if="item.widthChildren>0" class="lineAnimation-children"
							:style="{'width':item.widthChildren+'%'}">
						</view>
					</view>
				</view>
				<view class="schedule-number">{{schedule}}%</view>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		wycUrl,
		sslbiz,
		wycUrlApi,
		apiMixUrlApi
	} from '@/api/assemb.js'
	export default {
		data() {
			return {
				toneIndex: 0,
				toneList: [{
						text: '科幻/奇幻'
					},
					{
						text: '悬疑/推理'
					},
					{
						text: '爱情'
					},
					{
						text: '幽默'
					},
					{
						text: '历史/传记'
					},
					{
						text: '动作/战争'
					},
					{
						text: '幽默/喜剧'
					},
					{
						text: '青春/成长'
					},
					{
						text: '恐怖'
					},
					{
						text: '武侠'
					},
					{
						text: '军事'
					},
					{
						text: '耽美'
					},
				],
				styleIndex: 0,
				styleList: [{
						text: '简洁明了'
					},
					{
						text: '叙事复杂'
					},
					{
						text: '浪漫主义'
					},
					{
						text: '现实主义'
					},
					{
						text: '活泼诙谐'
					},
					{
						text: '异想天开'
					},
					{
						text: '古典主义'
					}
				],
				show: false,
				message: '',
				languageItem: '科幻/奇幻',
				toneItem: '',
				styleItem: '现实主义',
				writing: '',
				title: '',
				outline: '',
				answer: '猫咪眯着眼睛，舒服的坐在沙发上。格子图案的地板，全息\n' +
					'图，VR，3D感。猫咪眯着眼睛，舒服的坐在沙发上。格子\n' +
					'图案的地板，全息图，VR，3D感。',
				tabbarList: [

					{
						src: '/static/create/create_continue1.png',
						text: '重新生成'
					},
					{
						src: '/static/create/create_copy1.png',
						text: '复制文本'
					}
				],
				creativeResult: '',
				creativeResults: '',
				compareResults: '',
				originality: '',
				aiLevel: 0,
				width: 0,
				arrIndex: [],
				widthIndex: 0,
				schedule: 0,
				text: '创作中,请稍后',
				scheduleShow: false,
				isVip: false
			}
		},
		onShow() {
			this.isVip = uni.getStorageSync('vipType').vipStatus == 1 ? true : false;
		},
		onLoad(option) {},
		methods: {
			//进度条
			change() {
				clearTimeout(this.time);
				clearTimeout(this.time1);
				clearTimeout(this.times);
				var settext = [
					"创作中,请稍后",
					"优化中,请稍后",
					"下载中,请稍后",
					"合并中,请稍后",
					"上传中,请稍后"
				];
				let inx = 0;
				this.widthIndex = 0;
				this.schedule = 0;
				this.arrIndex = this.arrIndex.map(item => {
					return {
						...item,
						width: 100 / (this.arrIndex.length),
						widthChildren: 0
					};
				});

				// 计算总进度
				let sum = () => {
					let number = this.arrIndex
						.map((item) => item.widthChildren)
						.reduce((accumulator, currentValue) => accumulator + currentValue);
					this.schedule = Math.floor(number / this.arrIndex.length);
				};
				const loadNextProgress = () => {
					if (this.widthIndex >= this.arrIndex.length) {
						this.time = setTimeout(() => {
							this.widthIndex = 0; // 重置为0，从新循环
							console.log('下一个进度条')
							loadNextProgress();
						}, 100); // 等待 1s 后重新开始加载
						if (this.widthIndex >= this.arrIndex.length - 1) {
							this.arrIndex.forEach((item) => {
								item.widthChildren = 0;
							});
							inx += 1;
							if (inx > 4) {
								this.text = settext[4]
							} else {
								this.text = settext[inx]
							}
							this.schedule = 0;
							clearTimeout(this.time)
							this.time = null
						}
						this.time1 = setTimeout(() => {
							this.widthIndex = 0;
							loadNextProgress();
							clearTimeout(this.time1)
						}, 300);
						return;
					}
					if (this.widthIndex > 0) {
						// 如果是加载了第二个进度，则让上一个进度条伪 100%
						this.arrIndex[this.widthIndex - 1].widthChildren = 100;
					}
					if (this.arrIndex[this.widthIndex].widthChildren < 99) {
						this.arrIndex[this.widthIndex].widthChildren++;
						this.times = setTimeout(loadNextProgress, 300); // 间隔 100ms 执行下一次加载
					} else {
						this.widthIndex++; // 接着下一个进度跑
						loadNextProgress();
					}
					sum(); // 计算整体的进度值
				};
				loadNextProgress();
			},
			async original(param, i) {
				// uni.showLoading({
				//   title: '加载中...',
				//   mask: true
				// });
				console.log('2222')
				await wycUrl(param, 1009, 'magicChat').then((res) => {
					//   await wycUrl(param, 1005, 'chatAzure2').then((res) => {
					setTimeout(() => {
						this.scheduleShow = false
					}, 1000)
					if (res.data.code == 200) {
						this.writing = ''
						console.log('这是200的结果')
						let prams = {
							text: res.data.data.results[0]
						};
						sslbiz(prams, "1089", "DYTextCheck").then(async res => {
							console.log(res.hit, '这是返回结果的敏感词')
							if (res.hit) {
								res.data.data.results[0] = ''
								uni.showModal({
									title: '提示',
									content: "创作内容包含敏感词,系统已屏蔽！",
									success: function(res) {
										if (res.confirm) {
											console.log('用户点击确定');
										} else if (res.cancel) {
											console.log('用户点击取消');
										}
									}
								});
							}
						})
					} else if (res.data.code == 400) {
						this.writing = ''
						uni.showModal({
							title: '提示',
							content: res.data.message
						})
					} else {
						this.writing = ''
					}
					this.widthIndex++
					if (!this.isVip) {
						let param = {
							consumecoins: 1,
							descinfo: '一键创作消耗',
							consumetype: 1,
						}
						apiMixUrlApi(param, '1043', "ConsumeCoins").then(result => {
							console.log(result, '1043返回值');
							uni.setStorageSync('frequencyrs', result.coins)
						});
					}
					console.log('res=====>', res)
					this.creativeResult += res.data.data.results[0]
					this.show = true
					uni.hideLoading();
				}).catch(err => {
					setTimeout(() => {
						this.scheduleShow = false
					}, 1000)
					console.log('失败了~~', i, this.arrIndex[i], err)
					// this.scheduleShow = false
					let str = err
					if (str.slice(0, 12) == '') {
						str = str.slice(12)
					}
					console.log('str', str)
					let context = ''
					if (str.length > 20) {
						context = `${str.slice(0, 8)}......${str.slice(-8)}`
					} else {
						context = str
					}

					uni.showModal({
						title: '提示',
						content: `"${context}",以上内容含有违规，请整改`,
						showCancel: false,
						success: function(res) {
							if (res.confirm) {
								console.log('用户点击确定');
							} else if (res.cancel) {
								console.log('用户点击取消');
							}
						}
					});
				})
			},
			// AI伪原创
			async highOriginal() {
				if (this.writing.trim() == '') {
					uni.showToast({
						title: '请输入内容',
						duration: 2000,
						icon: 'none'
					});
				} else if (uni.getStorageSync('frequencyrs') > 0 || this.isVip) {
					console.log('走这儿了')
					let prams = {
						text: this.writing,
					};
					sslbiz(prams, "1089", "DYTextCheck").then(async res => {
						if (res.hit) {
							this.writing = ''
							uni.showModal({
								title: '提示',
								content: "检测到敏感关键词或文本为空，请修改后重试！",
								success: function(res) {
									if (res.confirm) {
										console.log('用户点击确定');
									} else if (res.cancel) {
										console.log('用户点击取消');
									}
								}
							});
						} else {
							if (this.writing.trim().length < 400 || this.isVip) {
								let str = this.writing,
									arr = [] //用于保存每次截取后的字符串
								biali(str, 0);
								console.log(arr);

								function biali(x, z) {
									var m = x.substr(z, 200);
									var f = ['。', ',', '.', '?', ';', '!', '，', '？', '！', '；'];
									var y = 200;
									var ynum = [];
									for (var j = 0; j < f.length; j++) {
										if (m.lastIndexOf(f[j]) > 0) {
											ynum.push(m.lastIndexOf(f[j]));
										}
									}
									if (ynum.length > 0) {
										y = (Math.max.apply(null, ynum) + 1);
									}
									arr.push(x.substr(z, y));
									z += y;
									if (m.length >= 200) {
										return biali(x, z);
									}
								}


								this.arrIndex = arr
								this.scheduleShow = true
								this.text = '创作中,请稍后'
								this.change()
								for (var i = 0; i < arr.length; i++) {


								}
								let param = {
									"promptId": 70,
									"conditions": [`${this.writing}`, `${this.message}`,
										`${this.languageItem}`, `${this.styleItem}`
									]
								}
								console.log('在浏览器中打开页面');
								await this.original(param, i)
								setTimeout(() => {
									this.scheduleShow = false
								}, 1000)
								uni.hideLoading();

							} else {
								uni.showToast({
									title: '字数超限了,开通会员不限字数。',
									duration: 2000,
									icon: 'none'
								});
								this.content = '字数超限了,开通会员不限字数。'
								this.vipShow = true
							}

						}
					})

				} else {
					this.isShowLoading = false;

					uni.showToast({
						title: '今日免费次数已用完,需开通会员才可使用',
						duration: 2000,
						icon: 'none'
					});
					// this.content = '今日免费次数已用完,需开通会员才可使用。'
					this.vipShow = true
				}
			},
			changeLanguage(item, index) {
				this.languageIndex = index
				this.languageItem = item.text
			},
			changeStyle(item, index) {
				this.styleIndex = index
				this.styleItem = item.text
			},
			changeTone(item, index) {
				this.toneIndex = index
				this.toneItem = item.text
			},
			select(e) {
				this.message = '500'
				this.writing = '仙侠，玄幻，虐恋，叶凡'
				this.styleIndex = 3
			},
			changeOutline(e) {
				this.outline = e.detail.value
			},
			changeMessage(e) {
				this.message = e.detail.value
			},
			changeTitle(e) {
				this.title = e.detail.value
			},
			changeValue(e) {
				this.writing = e.detail.value
			},
			async create() {

				if (!this.message) {
					uni.showToast({
						title: '请输入产品名称',
						icon: 'none',
						duration: 2000
					});
					return
				}
				if (!this.writing) {
					uni.showToast({
						title: '请输入产品特点',
						icon: 'none',
						duration: 2000
					});
					return
				}
				this.highOriginal();

			},
			clickTab(item, index) {
				if (index == 0) {
					this.show = false
				} else {
					let text = this.creativeResult
					// #ifdef H5
					let textarea = document.createElement("textarea")
					textarea.value = text
					textarea.readOnly = "readOnly"
					document.body.appendChild(textarea)
					textarea.select() // 选中文本内容
					textarea.setSelectionRange(0, text.length)
					uni.showToast({ //提示
						title: '复制成功',
						icon: 'success'
					})
					document.execCommand("copy")
					textarea.remove()
					// #endif
					// #ifndef H5
					uni.setClipboardData({
						data: text, //要被复制的内容
						success: () => { //复制成功的回调函数
							uni.showToast({ //提示
								title: `复制成功`,
								icon: 'success'
							})
						}
					}, true);
					// #endif

				}
			},
		},
	}
</script>

<style lang="less">
	.page {
		width: 100%;
		height: calc(100vh);
		background: #FDFDFD;
	}

	.scroll-Y {
		width: 100%;
		height: 100%;
	}

	.page-view {
		width: 100%;
		height: 100%;
	}

	.title {
		width: 100%;
		height: 80rpx;
		margin: 0 0 0 -20px;
		box-sizing: border-box;
		padding: 0rpx 40rpx;
		display: flex;
		align-items: center;
		//   background-color: #F7F7F7;
		font-size: 24rpx;
		color: #666666;
	}

	.context {
		width: 90%;
		margin: 0rpx auto;

		.context-tone {
			width: 100%;
			display: flex;
			flex-wrap: wrap;

			.context-tone-item {
				width: 18%;
				padding: 12rpx 14rpx;
				// background-color: #F7F7F7;
				border: 1px solid #FFEEF0;
				border-radius: 24rpx;
				font-size: 22rpx;
				background: #F8F8F8;
				//   margin-left: 15rpx;
				//   margin-right: 30rpx;
				//   margin-bottom: 30rpx;
				margin: 5px 0 0 8.3px;
				color: #333333;
				text-align: center;
			}

			.context-tone-item-select {
				//   background-color: #4BB591;
				background-color: #FFEEF0;
				color: #F1445D;
			}
		}

		.context-tip {
			width: 100%;
			height: 90rpx;
			margin-top: 10px;
			display: flex;
			justify-content: space-between;
			align-items: center;

			.context-tip-left {
				font-size: 30rpx;
				color: #333333;
				display: flex;
				align-items: center;

				/deep/.context-tip-left-tip span {
					color: red;
					margin-left: 6rpx;
					vertical-align: sub;
				}
			}

			.context-tip-right {
				color: #999999;
				font-size: 24rpx;
			}
		}

		.context-title {
			width: 100%;
			height: 90rpx;
			font-size: 30rpx;
			color: #333333;
			margin-top: 10px;
			display: flex;
			align-items: center;

			/deep/.context-title-tip span {
				color: red;
				margin-left: 6rpx;
				vertical-align: sub;
			}
		}

		.context-textarea {
			width: 100%;
			height: 240rpx;
			// background-color: #F7F7F7;
			// border: 1px solid #FFEEF0;
			border-radius: 24rpx;
			position: relative;

			.context-textarea-input {
				width: 100%;
				height: 100%;
				box-sizing: border-box;
				padding: 14rpx;
				color: #333333;
				font-size: 28rpx;
				background: #F8F8F8;
			}

			.context-textarea-max {
				position: absolute;
				right: 40rpx;
				bottom: 20rpx;
				color: #999999;
			}
		}

		.button {
			width: 90%;
			height: 90rpx;
			background-color: rgba(52, 116, 255, 0.3);
			border-radius: 60rpx;
			text-align: center;
			display: flex;
			align-items: center;
			justify-content: center;
			color: #fff;
			font-size: 30rpx;
			margin: 40rpx auto 30rpx;
		}
	}

	.btn {
		display: flex;
		position: fixed;
		flex-direction: row;
		border-radius: 25px 25px 0 0;
		width: 100%;
		bottom: 0px;
		z-index: 99;
		margin-left: -20px;
	}

	.placeholder {
		height: 50%;
		padding-bottom: 200rpx;
	}

	.answer {
		width: 90%;
		margin: 0px auto;
		height: 90%;

		.answer-fontLength {
			width: 100%;
			height: 60rpx;
			color: #999999;
			font-size: 30rpx;
			// display: flex;
			// align-items: center;
			//padding-left: 520rpx;
			position: absolute;
			left: 76%;
		}

		.answer-value {
			width: 100%;
			height: 100rpx;
			color: #333333;
			font-size: 44rpx;
			line-height: 100rpx;
			// display: flex;
			// align-items: center;
			white-space: nowrap;
			overflow: hidden;
			text-overflow: ellipsis;
		}

		.answer-textarea {
			position: relative;
			width: 100%;
			height: 85%;
			// background-color: #F7F7F7;
			border: 1px solid #FFEEF0;
			border-radius: 24rpx;

			.answer-textarea-input {
				width: 100%;
				height: 92%;
				box-sizing: border-box;
				padding: 30rpx 30rpx 20rpx;
				color: #333333;
				font-size: 28rpx;
			}
		}
	}

	.tabbar {
		width: 100%;
		//   height: 10%;
		//   background-color: #fff;
		display: flex;
		box-sizing: border-box;
		justify-content: center;

		//   border-top: 1rpx solid #e5dbdb;
		.tabbar-item {
			width: 33.33%;
			height: 68.84rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			// flex-direction: column;
			font-family: PingFang SC;
			padding: 0 40rpx;
			font-weight: 500;
			color: #fff;
			line-height: 36rpx;
			font-size: 24rpx;
			border: solid 2rpx;
			margin: 0 12rpx;
			background: linear-gradient(180deg, #E9556A 0%, #F97A8C 100%);
			border-radius: 34rpx;
		}
	}

	/deep/::-webkit-scrollbar {
		display: none;
		width: 0 !important;
		height: 0 !important;
		-webkit-appearance: none;
		background: transparent;
		color: transparent;
	}

	.schedule-page {
		width: 100%;
		height: 100vh;
		position: fixed;
		background-color: rgba(128, 126, 126, 0.8);
		top: 0px;
		left: 0px;
		display: flex;
		justify-content: center;
		align-items: center;
		z-index: 200;
	}

	.schedule-box {
		width: 62%;
		background-color: #fff;
		border-radius: 15rpx;
	}

	.schedule-text {
		text-align: center;
		line-height: 120rpx;
	}

	.schedule {
		width: 100%;
		height: 20rpx;
		margin: 20rpx 0rpx;
	}

	.schedule-number {
		width: 100%;
		height: 100rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		color: #2979ff;
	}

	.lineBox {
		width: 90%;
		display: flex;
		justify-content: space-around;
		margin: 0px auto;
		height: 12rpx;
		border-radius: 24rpx;
		overflow: hidden;
	}

	.lineAnimation {
		height: 100%;
		background-color: #bbb9b9;
	}

	.lineAnimation-children {
		height: 100%;
		transition: all 0.5s;
		background-color: #2979ff;
	}

	.baifenbizdy {
		color: skyblue;
		font-size: 22px;
		align-items: center;
		justify-content: center;
		display: flex;
		margin-top: 7%;
	}

	.isshow {
		background-color: #fff;
		border-radius: 10px;
		width: 90%;
		height: 190px;
		left: 5%;
		position: relative;
		top: -70%;
		font-size: 50px;
		z-index: 10086;
		color: #1890ff;
		padding: 40px 0 0 0;
	}

	.box {
		width: 880px;
		background: #ffffff;
		position: relative;
		// height: 640px;
	}

	.textzdy {
		display: flex;
		font-size: 22px;
		margin: auto;
		color: grey;
		align-items: center;
		justify-content: center;
		padding-top: 2%;
	}

	.container {
		width: 90%;
		height: 7px;
		background-color: #fafafc;
		border-radius: 15px;
		margin-left: 5%;
		margin-top: 8%;
	}

	/* 内部加载部分样式 */
	.contentzdy {
		width: 100%;
		height: 7px;
		border-radius: 15px;
		background-color: #1890ff;
		text-align: center;
		line-height: 10px;
	}

	.jindu {
		margin-top: 1px;
	}
</style>